package com.inwavetech.os.tests.sync;

import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;

import com.inwavetech.os.entity.Os;
import com.inwavetech.os.entity.Product;
import com.inwavetech.os.entity.User;
import com.inwavetech.os.sync.FinishedOsRemover;
import com.inwavetech.os.util.DaoHelper;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by jgskin on 3/12/14.
 */
public class FinishedOsRemoverTest extends AndroidTestCase {

    private Dao<Os, ?> osDao;
    private Dao<Product, ?> productDao;
    private Dao<User, ?> userDao;
    private DaoHelper daoHelper;

    @Override
    protected void setUp() throws Exception {
        RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_");
        daoHelper = new DaoHelper(context);
        osDao = daoHelper.getDao(Os.class);
        productDao = daoHelper.getDao(Product.class);
        userDao = daoHelper.getDao(User.class);
    }

    public void testOnly() throws Exception {
        User user = new User();
        user.username = "welcometomylife";
        userDao.create(user);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        calendar.add(Calendar.HOUR, -1);

        Date oneDayBack = calendar.getTime();
        createOs("1", oneDayBack, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);
        createOs("2", oneDayBack, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);
        createOs("3", oneDayBack, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);
        createOs("4", oneDayBack, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);

        Date nowDate = new Date();
        createOs("5", nowDate, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);
        createOs("6", nowDate, user, Os.Status.FINISHED, Os.ServiceOrderType.INSTALL);

        createOs("7", oneDayBack, user, Os.Status.ACTIVE, Os.ServiceOrderType.INSTALL);
        createOs("8", oneDayBack, user, Os.Status.ACTIVE, Os.ServiceOrderType.INSTALL);

        (new FinishedOsRemover(daoHelper)).execute();

        assertEquals(4, osDao.countOf());
        assertEquals(4, productDao.countOf());
    }

    private void createOs(String id, Date osDate, User user, Os.Status status, Os.ServiceOrderType serviceOrderType) throws SQLException {
        Os os = new Os();
        os.original_id = id;
        os.finished_at = osDate;
        os.user = user;
        os.status = status;
        os.service_order_type = serviceOrderType;
        os.send_to_server = false;

        osDao.create(os);

        Product product = new Product();
        product.original_id = id;
        product.os = os;

        productDao.create(product);
    }
}
